<?php

class phone{

	 /**
     * 手机号发送验证码
     * @param string phone 手机号
     * @param string module 模板
     */
	public static function sendPhoneCode($phone,$module,$recall=''){
		//生成验证码
		$char = "0,1,2,3,4,5,6,7,8,9";
        $list = explode(",", $char);
        $code = '';
        for ($i = 0; $i < 4; $i++) {
            $randnum = rand(0, 9);
            $code .= $list[$randnum];
        }
        $templateParam['code'] = $code;
        $templateParam = json_encode($templateParam);
        $message = '验证码：'.$code;
        //$code = 123456;
        $redis = new Redis();
        if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
            && $redis->auth(C('REDIS_PASSWORD')) == TRUE
            && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
        ){
        	if ($redis->get($phone.'code')){
        		$return['code'] = 1;
	            $return['msg'] = '验证码发送间隔不能少于60秒';
	            $return['data'] = [];
	            Output::instance()->object($return);
	            return;
        	}
            $redis->set($phone.'code', $code);
            $redis->expire($phone.'code', 60);

            $redis->set($phone, $code);
            $redis->expire($phone, 180);
        }
        self::sendSms($phone,$module,'code',$message,$templateParam,$recall);
	}

	public static function  sendSms($phone,$module,$status,$message,$templateParam='',$recall='') {
        /** 1. 实例化数据库 */
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $sms = M("customer_sms_setting");
        $user = M("customer_user");
        $moduleGroup = M("module_group");
        Session::switchCustomer($customerId);

        //调取获取参数接口
        $plat = self::checkSystemSms($status);
        log::write('mm__plat'.json_encode($plat));
        if ($recall && $plat['code']) {
            Output::instance()->object($plat);
        }
        if ($plat['code']) {
            return;
        }
        //调用阿里云发送接口，获取一大堆参数【手机号、短信签名、短信模板id、code，以及那Access Key ID	Access Key Secret】
        $Alisms = A("Alisms");
        //发送短信
        $send_result = $Alisms->send_verify($phone,$plat,$templateParam);
        log::write('mm__send_result'.json_encode($send_result));
        $channel = $plat['smsServiceType'];
        $moduleInfo = $moduleGroup->field('id,name')->where("modules='$module'")->find();
        $moduleId = $moduleInfo['id'];
        $moduleName = $moduleInfo['name'];
        //根据发送情况分别处理发送成功和失败之后的逻辑
        if ($send_result['Code'] == 'OK'){
            self::addSmsRecord($moduleId,$moduleName,$channel,$phone,$message,'ok',$send_result['BizId'],$status);
            if ($channel == 'ali'){
                $sms->where("cid=$customerId")->setInc("aliSendNumber");
            }else if($channel == 'system'){
                $sms->where("cid=$customerId")->setInc("totalSendNumber");
                $sms->where("cid=$customerId")->setDec("surplusNumber");
            }
            if ($recall) {
                $return['code'] = 0;
                $return['msg'] = '短信发送成功';
                $return['data'] = [];
                Output::instance()->object($return);
            }
        }else{
            self::addSmsRecord($moduleId,$moduleName,$channel,$phone,$message,$send_result['error'],'',$status);
            if ($channel == 'ali'){
                //发送站内信,需发送用户信息查询
                $where_user['customerId'] = $customerId;
                $where_user['agent'] = 'business';
                $where_user['status'] = 'open';
                $userId = $user->where($where_user)->getField('id');
                $message = '尊敬的用户您好，您的阿里云账户'.$send_result['error'].'导致短信服务无法正常使用，请及时前往阿里云官方平台进行处理。';
                $Act_action = A("PlatMessage");
                $Act_action::pushMessage('短信服务异常通知', $message, array($userId), '', 0, 'smsCenter', '短信中心', 1, 0, $callType = 0, $sendType = 0);
                if ($recall) {
                    $return['code'] = 1;
                    $return['msg'] = '短信发送失败，'.$send_result['error'];
                    $return['data'] = [];
                    Output::instance()->object($return);
                }

            }else if ($channel == 'system') {
                //发送站内信,需发送用户信息查询
                $where_user['customerId'] = $customerId;
                $where_user['agent'] = 'business';
                $where_user['status'] = 'open';
                $userId = $user->where($where_user)->getField('id');
                $message = '尊敬的用户您好，系统短信服务'.$send_result['error'].'导致短信服务无法正常使用，请及时联系系统管理员进行处理。';
                $Act_action = A("PlatMessage");
                $Act_action::pushMessage('短信服务异常通知', $message, array($userId), '', 0, 'smsCenter', '短信中心', 1, 0, $callType = 0, $sendType = 0);
                if ($recall) {
                    $return['code'] = 1;
                    $return['msg'] = '短信发送失败，'.$send_result['error'];
                    $return['data'] = [];
                    Output::instance()->object($return);
                }
            }
        }
    }
 	/**
     * 验证手机号验证码
     * @param string phone 
     * @param string code 
     * @param int recall 调用方式为1为外部调用 
     */
	public static function verifyPhoneCode($phone,$code,$recall=NULL){
       
	   /** 1.连接redis */
	   $redis = new Redis();
	   if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
	      && $redis->auth(C('REDIS_PASSWORD')) == TRUE
	      && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
	   ){
        //判断验证码是否正确
          $redisCode = $redis->get($phone);
          if($redisCode == $code){
            $redis->set('verify_'.$phone, true);
            $redis->expire('verify_'.$phone, 60);
             if ($recall){
                $return['code'] = 0;
                $return['msg'] = '验证码验证成功';
                $return['data'] = [];
                Output::instance()->object($return);
             }else{
                return true;
            }            
          }else{
            $redis->set('verify_'.$phone, false);
            $redis->expire('verify_'.$phone, 60);
            if ($recall){
                $return['code'] = 1;
                $return['msg'] = '验证码验证失败';
                $return['data'] = [];
                Output::instance()->object($return);
             }else{
                return false;
            }   
          }
       } 
	}

    /**
     * 验证手机号是否通过验证码验证
     * @param string phone 
     */
    public static function verifyPhone($phone){
          /** 1. 实例化数据库 */
        $customerId = Session::$user["customerId"];
        Session::switchCustomer($customerId);
        $user = M('user');

       /** 2.连接redis */
       $redis = new Redis();
       if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
          && $redis->auth(C('REDIS_PASSWORD')) == TRUE
          && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
       ) {
        //判断手机验证是否正确
          $redisCode = $redis->get('verify_'.$phone);
          if($redisCode){            
                return true;                   
          }else{ 
            //如果没有验证过的话需要去user表中查此手机号
            $where_user['isVerifyPhone'] = 1;          
            $where_user['phone'] = $phone;
            $verify = $user->where($where_user)->find();  
            if ($verify){
                return true;   
            }else{
                $return['code'] = 1;
                $return['msg'] = '手机号验证失败';
                $return['data'] = [];
                Output::instance()->object($return);
                exit();
            }        
                         
          }
       }
    }

    /**
     * 验证平台是否可以发送短信
     * @param string type 发送什么类型短信
     */
    public static function checkSystemSms($type){
        /**1.数据表模型*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $sms= M('customer_sms_setting');
        $user= M('customer_user');
        $smsTemplate = M('sms_template');
        Session::switchCustomer($customerId);
        /**3.短信配置查询*/
        $smsInfo = $sms->where("cid=$customerId")->find();
        log::write('mm__smsInfo'.json_encode($smsInfo).$sms->getLastSql());
        //判断平台是否开启短信配置相关，如果没有的话不允许发送短信、
        if(empty($smsInfo)){
            $return['code'] = 1;
            $return['msg'] = '此账号没有开通短信服务，不可发送短信';
            $return['data'] = [];
            return $return;
        }else{
            //判断用户是使用系统短信服务还是使用阿里云短信服务
            if ($smsInfo['smsServiceType'] == 'system'){
                $plat = $sms->field('accessKeyId,accessKeySecret')->where("isPlatParameter=1")->find();
                 //查询平台短信模板消息
                $where_template['isPlatParameter'] = 1;
                $where_template['status'] = $type;
                $where_template['open'] = 1;
                $templateInfo = $smsTemplate->field('signName,templateCode')->where($where_template)->find();
                if (empty($templateInfo)){
                    $return['code'] = 1;
                    $return['msg'] = '此账号没有开通此状态短信服务，不可发送短信';
                    $return['data'] = [];
                    return $return;
                }
                $plat['signName'] = $templateInfo['signName'];
                $plat['templateCode'] = $templateInfo['templateCode'];
                $plat['smsServiceType'] = 'system';
                //首先判断短信剩余条数是不是到提醒条数,大于的话则直接发送
                if($smsInfo['surplusNumber'] > $smsInfo['surplusNumberRemind']){
                    return $plat;
                }else{
                    //判断是否需要提醒,如果已经到了0条则只提醒不发送。
                    $notice=0;
                    for($i=0;$i <= 10;$i++){
                        $noticeNumber = ceil(($smsInfo['surplusNumber'] * $i * 0.1));
                        if ($noticeNumber == $smsInfo['surplusNumber']){
                            $notice = 1;
                            break;
                        }
                    } 
                    if ($notice){
                        //发送站内信,需发送用户信息查询
                        $where_user['customerId'] = $customerId;
                        $where_user['agent'] = 'business';
                        $where_user['status'] = 'open';
                        $userId = $user->where($where_user)->getField('id');
                        $message = '尊敬的用户您好，您的短信条数已剩余'.$smsInfo['surplusNumber'].'条，为了不影响您使用系统短信服务，请及时联系平台管理员进行短信充值。';
                        $Act_action = A("PlatMessage");
                        $Act_action::pushMessage('短信剩余条数提醒', $message, array($userId), '', 0, 'smsCenter', '短信中心', 1, 0, $callType = 0, $sendType = 0);

                    }
                    if($smsInfo['surplusNumber'] == 0){
                        //程序不继续执行
                        $return['code'] = 1;
                        $return['msg'] = '此账号剩余短信条数为0，不可发送短信';
                        $return['data'] = [];
                        return $return;
                    }else{
                        return $plat;
                    }
                }
               
            }else{
                $plat['accessKeyId'] = $smsInfo['accessKeyId'];
                $plat['accessKeySecret'] = $smsInfo['accessKeySecret'];
                //查询平台短信模板消息
                $where_template['cid'] = $customerId;
                $where_template['status'] = $type;
                $where_template['open'] = 1;
                $templateInfo = $smsTemplate->field('signName,templateCode')->where($where_template)->find();
                if (empty($templateInfo)){
                    $return['code'] = 1;
                    $return['msg'] = '此账号没有开通此状态短信服务，不可发送短信';
                    $return['data'] = [];
                    return $return;
                }
                $plat['signName'] = $templateInfo['signName'];
                $plat['templateCode'] = $templateInfo['templateCode'];
                $plat['smsServiceType'] = $smsInfo['smsServiceType'];
                return $plat;
            }

        }
    }


    /**
     * [短信发送记录表数据添加]
     * @param int $moduleId   模块id
     * @param string $moduleName   模块名称
     * @param string $channel   发送渠道
     * @param string $phone   手机号
     * @param string $content   发送内容
     * @param string $requestResult   请求结果
     * @param string $bizId   回执id
     */
    public static function addSmsRecord($moduleId,$moduleName,$channel,$phone,$content,$requestResult,$bizId='',$status)
    {
         /** 1. 实例化数据库 */
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $record = M("sms_send_record");
        Session::switchCustomer($customerId);

        /** 3.  数据处理 */
        $time =  date('Y-m-d H:i:s',time());
        $add_record['cid'] = $customerId;
        $add_record['moduleName'] = $moduleName;
        $add_record['moduleId'] = $moduleId;
        $add_record['channel'] = $channel;
        $add_record['phone'] = $phone;
        $add_record['content'] = $content;
        $add_record['requestResult'] = $requestResult;
        $add_record['createTime'] = $time;
        $add_record['updateTime'] = $time;
        $add_record['bizId'] = $bizId;
        $add_record['status'] = $status;
        $add_result = $record->add($add_record);

        return $add_result;
    }




}